package com.example.com.transcribeeditpublish.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.com.transcribeeditpublish.PlayState;
import com.example.com.transcribeeditpublish.R;
import com.example.com.transcribeeditpublish.TCVideoEditerWrapper;
import com.example.com.transcribeeditpublish.views.VideoWorkProgressFragment;
import com.example.com.transcribeeditpublish.databinding.ActivityPictureEditBinding;
import com.example.com.transcribeeditpublish.popuWindow.FilterPpwindow;
import com.example.com.transcribeeditpublish.popuWindow.MusicListPpwindow;
import com.example.com.transcribeeditpublish.utils.TCConstants;
import com.example.com.transcribeeditpublish.utils.TCEditerUtil;
import com.tencent.liteav.basic.log.TXCLog;
import com.tencent.ugc.TXVideoEditConstants;
import com.tencent.ugc.TXVideoEditer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.example.com.transcribeeditpublish.BR;
import com.tencent.ugc.TXVideoInfoReader;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.utils.BaseUrlExternalStrageDir;

/**
 * Created by i7-1 on 2018/12/11.
 */

public class PictureEditerActivity extends BaseActivity<ActivityPictureEditBinding, BaseViewModel> implements TCVideoEditerWrapper.TXVideoPreviewListenerWrapper, TXVideoEditer.TXVideoGenerateListener {

    private ArrayList<String> picPathList;
    private ArrayList<Bitmap> bitmapList;
    private TXVideoEditer mTXVideoEditer;
    private TCVideoEditerWrapper mEditerWrapper;
    private long mVideoDuration;
    private int mCurrentState = PlayState.STATE_NONE;       // 播放器当前状态
    private String TAG = "PictureEditerActivity";
    private FilterPpwindow filterPpwindow;

    private static final int[] FILTER_ARR = {
            R.drawable.filter_biaozhun, R.drawable.filter_yinghong,
            R.drawable.filter_yunshang, R.drawable.filter_chunzhen,
            R.drawable.filter_bailan, R.drawable.filter_yuanqi,
            R.drawable.filter_chaotuo, R.drawable.filter_xiangfen,
            R.drawable.filter_langman, R.drawable.filter_qingxin,
            R.drawable.filter_weimei, R.drawable.filter_fennen,
            R.drawable.filter_huaijiu, R.drawable.filter_landiao,
            R.drawable.filter_qingliang, R.drawable.filter_rixi};
    private MusicListPpwindow musicListPpwindow;
    private String mVideoOutputPath;
    private VideoWorkProgressFragment mWorkLoadingProgress;

    @Override
    public void onPreviewProgressWrapper(int time) {
        //Log.e("onPreviewProgress = ", time + "");
    }

    @Override
    public void onPreviewFinishedWrapper() {
        Log.e("Finished = ", "Finished");

        stopPlay();

        startPlay(getCutterStartTime(), getCutterEndTime());
    }




    @Override
    public int initContentView() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.activity_picture_edit;
    }

    @Override
    public int initVariableId() {
        return BR.entity;
    }

    @Override
    public BaseViewModel initViewModel() {
        return new BaseViewModel(this);
    }

    @Override
    public void initData() {
        super.initData();
        initVideo();
        initPlayerLayout();
        initListener();
    }

    private void initVideo() {
        mEditerWrapper = TCVideoEditerWrapper.getInstance();
        picPathList = getIntent().getStringArrayListExtra(TCConstants.INTENT_KEY_MULTI_PIC_LIST);
        decodeFileToBitmap(picPathList);
        mTXVideoEditer = new TXVideoEditer(this);
        mEditerWrapper.setEditer(mTXVideoEditer);
        int result = mTXVideoEditer.setPictureList(bitmapList, 20);
        if (result == TXVideoEditConstants.PICTURE_TRANSITION_FAILED) {
            Toast.makeText(this, "图片设置异常，结束编辑", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        // 注意：
        // 1、接口调用顺序：setPictureList在前，setPicTransferType在后，必须顺序调用
        // 1、图片转视频的时长需要设置转场类型后获取，因为不同的转场类型时长会不一样
        // 2、宽高信息sdk内部会处理成9：16比例，上层只有在加片尾水印的时候算归一化坐标用到，所以这里可以设置成720P（720 * 1280）或者540P（540 * 960）来计算。注意最终视频的分辨率是按照生成时传的参数决定的。
        // （5.0以前版本是按照第一张图片的宽高来决定最终的宽高，导致的问题是如果第一张图片有一边比较短，后面的图片会以最短边等比例缩放，显示出来就小了）
        mVideoDuration = mTXVideoEditer.setPictureTransition(TXVideoEditConstants.TX_TRANSITION_TYPE_LEFT_RIGHT_SLIPPING);
        TXVideoEditConstants.TXVideoInfo txVideoInfo = new TXVideoEditConstants.TXVideoInfo();
        txVideoInfo.duration = mVideoDuration;
        txVideoInfo.width = 720;
        txVideoInfo.height = 1280;
        mEditerWrapper.setTXVideoInfo(txVideoInfo);
        mEditerWrapper.setCutterStartTime(0, mVideoDuration);

    }


    private void decodeFileToBitmap(List<String> picPathList) {
        if (picPathList == null) {
            return;
        }
        bitmapList = new ArrayList<>();
        for (int i = 0; i < picPathList.size(); i++) {
            String filePath = picPathList.get(i);
            Bitmap bitmap = TCEditerUtil.decodeSampledBitmapFromFile(filePath, 720, 1280);
            bitmapList.add(bitmap);
            TCVideoEditerWrapper.getInstance().addThumbnailBitmap(0, bitmap);
        }
    }

    private void initPlayerLayout() {
        TXVideoEditConstants.TXPreviewParam param = new TXVideoEditConstants.TXPreviewParam();
        param.videoView = getBinding().videoPlayerLayout;
        //param.renderMode = TXVideoEditConstants.PREVIEW_RENDER_MODE_FILL_EDGE;
        param.renderMode = TXVideoEditConstants.PREVIEW_RENDER_MODE_FILL_SCREEN;
        mTXVideoEditer.initWithPreview(param);
    }

    /**
     * 如果是滤镜特效的界面调用：
     * 1、在播放状态下，按住滤镜不会停止播放
     * 2、播放到末尾了，按住时，不会重新播放
     *
     * @param
     */
    public void playVideo() {
        TXCLog.i(TAG, "editer_ib_play clicked, mCurrentState = " + mCurrentState);
        if (mCurrentState == PlayState.STATE_NONE || mCurrentState == PlayState.STATE_STOP) {
            startPlay(getCutterStartTime(), getCutterEndTime());
        } else {
            //  pausePlay();
        }
    }

    public void startPlay(long startTime, long endTime) {
        if (mCurrentState == PlayState.STATE_NONE || mCurrentState == PlayState.STATE_STOP) {
            mTXVideoEditer.startPlayFromTime(startTime, endTime);
            mCurrentState = PlayState.STATE_PLAY;
            //isPreviewFinish = false;
            //mIbPlay.setImageResource(R.drawable.ic_pause);
        }
    }

    public void pausePlay() {
        if (mCurrentState == PlayState.STATE_RESUME || mCurrentState == PlayState.STATE_PLAY) {
            mTXVideoEditer.pausePlay();
            mCurrentState = PlayState.STATE_PAUSE;
        }
    }

    public void stopPlay() {
        if (mCurrentState == PlayState.STATE_RESUME || mCurrentState == PlayState.STATE_PLAY ||
                mCurrentState == PlayState.STATE_PAUSE) {
            mTXVideoEditer.stopPlay();
            mCurrentState = PlayState.STATE_STOP;
        }

    }

    private long getCutterStartTime() {
        return mEditerWrapper.getCutterStartTime();
    }

    private long getCutterEndTime() {
        return mEditerWrapper.getCutterEndTime();
    }


    private void initListener() {
        getBinding().pBeautiful.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFilterPpwindow();
            }
        });

        getBinding().pMusic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMusicListPpwindow();
            }
        });

        getBinding().next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startGenerateVideo();
            }
        });
    }

    private void showMusicListPpwindow() {
        if (musicListPpwindow == null) {
            musicListPpwindow = new MusicListPpwindow(this, new MusicListPpwindow.BGMCallBack() {
                @Override
                public void select() {
                    stopPlay();
                    startPlay(getCutterStartTime(), getCutterEndTime());
                }
            });
        }
        musicListPpwindow.showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }

    private void showFilterPpwindow() {
        if (filterPpwindow == null) {
            filterPpwindow = new FilterPpwindow(this, new FilterPpwindow.FilterCallBack() {
                @Override
                public void callback(int position) {
                    setFilter(position);
                }
            });
        }

        filterPpwindow.showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }

    private void setFilter(int position) {
        Bitmap bitmap = null;
        if (position == 0) {
            bitmap = null;  // 没有滤镜
        } else {
            bitmap = BitmapFactory.decodeResource(getResources(), FILTER_ARR[position - 1]);
        }
        // 设置滤镜图片
        TCVideoEditerWrapper.getInstance().getEditer().setFilter(bitmap);
    }


    /**
     * =========================================视频生成相关==========================================
     */
    private void startGenerateVideo() {
        stopPlay(); // 停止播放
        mTXVideoEditer.cancel(); // 注意：生成时，停止输出缩略图

        // 处于生成状态
        mCurrentState = PlayState.STATE_GENERATE;
        // 防止
        getBinding().next.setEnabled(false);
        getBinding().next.setClickable(false);
        // 生成视频输出路径
        mVideoOutputPath = TCEditerUtil.generateVideoPath();

        if (mWorkLoadingProgress == null) {
            initWorkLoadingProgress();
        }
        mWorkLoadingProgress.setProgress(0);
        mWorkLoadingProgress.setCancelable(false);
        mWorkLoadingProgress.show(getSupportFragmentManager(), "progress_dialog");

        // 添加片尾水印
        //   addTailWaterMark();

        mTXVideoEditer.setCutFromTime(getCutterStartTime(), getCutterEndTime());
        mTXVideoEditer.setVideoGenerateListener(this);

//        if (mCustomBitrate != 0) { // 是否自定义码率
//            mTXVideoEditer.setVideoBitrate(mCustomBitrate);
//        }
        mTXVideoEditer.generateVideo(TXVideoEditConstants.VIDEO_COMPRESSED_720P, mVideoOutputPath);

    }

    private void stopGenerate() {
        if (mWorkLoadingProgress != null) {
            mWorkLoadingProgress.setProgress(0);
            mWorkLoadingProgress.dismiss();
        }
        if (mCurrentState == PlayState.STATE_GENERATE) {
            getBinding().next.setEnabled(true);
            getBinding().next.setClickable(true);
            Toast.makeText(this, "取消视频生成", Toast.LENGTH_SHORT).show();

            mCurrentState = PlayState.STATE_NONE;
            if (mTXVideoEditer != null) {
                mTXVideoEditer.cancel();
            }
        }
    }


    @Override
    public void onGenerateProgress(float progress) {
        mWorkLoadingProgress.setProgress((int) (progress * 100));
    }

    @Override
    public void onGenerateComplete(TXVideoEditConstants.TXGenerateResult result) {
        if (result.retCode == TXVideoEditConstants.GENERATE_RESULT_OK) {
            // 生成成功
            createThumbFile(result);
        } else {
            Toast.makeText(this, result.descMsg, Toast.LENGTH_SHORT).show();
            mWorkLoadingProgress.dismiss();
        }
        getBinding().next.setEnabled(true);
        getBinding().next.setClickable(true);
        mCurrentState = PlayState.STATE_NONE;
    }

    /**
     * 创建缩略图，并跳转至视频预览的Activity
     */
    private void createThumbFile(final TXVideoEditConstants.TXGenerateResult result) {

        AsyncTask<Void, String, String> task = new AsyncTask<Void, String, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                File outputVideo = new File(mVideoOutputPath);
                if (!outputVideo.exists())
                    return null;
                Bitmap bitmap = TXVideoInfoReader.getInstance().getSampleImage(0, mVideoOutputPath);
                if (bitmap == null)
                    return null;
                String folder = BaseUrlExternalStrageDir.getBaseUrl() + File.separator+"video";

                File appDir = new File(folder);
                if (!appDir.exists()) {
                    appDir.mkdirs();
                }

                String fileName = "thumbnail" + ".jpg";
                File file = new File(appDir, fileName);
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return file.getAbsolutePath();
            }

            @Override
            protected void onPostExecute(String s) {
                startPreviewActivity(result, s);
            }

        };
        task.execute();
    }

    private void startPreviewActivity(TXVideoEditConstants.TXGenerateResult result, String thumbPath) {

        Intent intent = new Intent(this, PreviewActvity.class);
        // intent.putExtra(TCConstants.VIDEO_RECORD_TYPE, TCConstants.VIDEO_RECORD_TYPE_EDIT);
        intent.putExtra(TCConstants.VIDEO_RECORD_VIDEPATH, mVideoOutputPath);
        if (thumbPath != null)
            intent.putExtra(TCConstants.VIDEO_RECORD_COVERPATH, thumbPath);
        intent.putExtra(TCConstants.VIDEO_RECORD_DURATION, getCutterEndTime() - getCutterStartTime());
        startActivity(intent);
        finish();
    }

    /**
     * ==========================================进度条==========================================
     */
    private void initWorkLoadingProgress() {
        if (mWorkLoadingProgress == null) {
            mWorkLoadingProgress = new VideoWorkProgressFragment();
        }
        mWorkLoadingProgress.setProgress(0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mEditerWrapper.addTXVideoPreviewListenerWrapper(this);
        playVideo();
    }

    @Override
    protected void onPause() {
        super.onPause();
        pausePlay();
        // 若当前处于生成状态，离开当前activity，直接停止生成
        if (mCurrentState == PlayState.STATE_GENERATE) {
            stopGenerate();
        }
        mEditerWrapper.removeTXVideoPreviewListenerWrapper(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mTXVideoEditer != null) {
            stopPlay();
            mTXVideoEditer.setVideoGenerateListener(null);
            //编辑完成后，销毁资源，避免影响处理下一个视频
            mTXVideoEditer.release();
            mTXVideoEditer = null;
        }
        // 清除对TXVideoEditer的引用以及相关配置
        mEditerWrapper.removeTXVideoPreviewListenerWrapper(this);
        mEditerWrapper.cleaThumbnails();
        mEditerWrapper.clear();
    }


}
